<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="供货商名称">
                <a-input placeholder="请输入供货商名称" v-model="queryParam.name" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input placeholder="请输入手机号" v-model="queryParam.tel" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="0"> 未审核 </a-radio-button>
          <a-radio-button value="1"> 已通过 </a-radio-button>
          <a-radio-button value="2"> 已拒绝 </a-radio-button>
        </a-radio-group>
        <div>
          <!-- <a-button type="primary" @click="$router.push({ path: '/saas/supplierPurchase/supplier/edit' })"
            >+ 新增</a-button
          >
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allDelete">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown> -->
        </div>
      </div>
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button v-if="!disabled" type="primary" @click="showCreated = true">+ 新增</a-button>
      </div>

      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
        :scroll="{ x: 'max-content' }"
      >
        <div slot="user" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.user.avatar_url" alt="" />
            </div>
            <div class="info">
              <span>{{ record.supplier_name }}</span>
              <span>{{ record.type == '0' ? '个人' : record.type == '1' ? '企业' : '个体工商户' }}</span>
            </div>
          </div>
        </div>
        <span slot="addtime" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <span slot="status" slot-scope="text">
          <div class="tagBox">
            <span class="tag" :style="text | orderStatus"></span>
            <span>{{ getStatus(text) }} </span>
          </div>
        </span>
        <div slot="action" slot-scope="scope" v-if="parseInt(scope.status) !== 2 && !disabled">
          <template v-if="parseInt(scope.status) === 1">
            <a-button type="link" @click="onInSupplier(scope)" size="small">进入</a-button>
            <a-button type="link" @click="toEdit(scope)" size="small">编辑</a-button>
            <a-divider type="vertical" style="margin: 0 1px" />
          </template>

          <a-dropdown>
            <a-button type="link" size="small">更多<a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item v-if="parseInt(scope.status) === 1">
                <a-button type="link" size="small" @click="delSupplier(scope, 0)">删除</a-button>
              </a-menu-item>
              <template v-else-if="parseInt(scope.status) === 0">
                <a-menu-item>
                  <a-button type="link" size="small" @click="delSupplier(scope, 1)">同意</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" size="small" @click="delSupplier(scope, 2)">拒绝</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" size="small" @click="toEdit(scope, 1)">查看</a-button>
                </a-menu-item>
              </template>
            </a-menu>
          </a-dropdown>
        </div>
      </a-table>
    </a-card>
    <!-- 创建供货商弹窗 -->
    <a-modal
      :title="businessForm.id ? '编辑供货商' : '创建供货商'"
      width="800px"
      v-model="showCreated"
      @ok="editSupplier"
      :afterClose="closeModal"
      :destroyOnClose="true"
      :confirmLoading="btnLoading"
    >
      <a-form-model
        ref="ruleForm"
        :model="businessForm"
        :rules="businessRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="供货商名称" prop="supplier_name">
          <a-input v-model="businessForm.supplier_name" :disabled='disabled_edit' placeholder="请选择供货商名称" />
          <p class="tip">供货商名称长度为4~30个字符，一个中文等于2个字符。</p>
        </a-form-model-item>
        <a-form-model-item label="供货商logo" prop="logo">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                if (disabled_edit) {
                  return
                }
                businessForm.logo = e.data
              }
            "
            @deleteImg="() => {
              if (disabled_edit) {
                return
              }
              businessForm.logo = ''
            }"
            :imgSrc="businessForm.logo"
            imgSizeText="144px*144px"
          >
          </cyyUploadImg>
          <p class="tip">
            logo不允许涉及政治敏感与色情。图片格式必须为:png.bmp.jpeg.gif;不可大于2m;建议使用png格式图片,以保持最佳效果;
          </p>
        </a-form-model-item>
        <a-form-model-item label="登录账号" prop="name">
          <a-input v-model="businessForm.name" :disabled="!!businessForm.id || disabled_edit" placeholder="请填写登录账号" />
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password" v-if="!businessForm.id">
          <a-input v-model="businessForm.password" placeholder="请输入密码" />
        </a-form-model-item>
        <a-form-model-item label="密码" v-else>
          <a-input v-model="businessForm.password" :disabled='disabled_edit' placeholder="" />
        </a-form-model-item>

        <a-form-model-item label="手机号" prop="tel">
          <a-input v-model="businessForm.tel" :disabled='disabled_edit' placeholder="请输入手机号" />
          <p class="tip">此项不能和云仓手机号一致</p>
        </a-form-model-item>

        <a-form-model-item label="地区" required>
          <Address v-model="address_info"  :disabled='disabled_edit'></Address>
        </a-form-model-item>

        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="businessForm.email" :disabled='disabled_edit' placeholder="请输入邮箱" />
        </a-form-model-item>
        <a-form-model-item label="售后时间" prop="sale_day">
          <a-input-number
            style="width: 200px; margin-right: 10px"
            v-model="businessForm.sale_day"
            :disabled='disabled_edit'
            placeholder="请输入售后时间"
          />
          <span>天</span>
        </a-form-model-item>
        <a-form-model-item label="抽成比例" prop="rate">
          <a-input-number
            :disabled='disabled_edit'
            style="width: 200px; margin-right: 10px"
            v-model="businessForm.rate"
            :max="100"
            :min="0"
            :precision="2"
            placeholder="请输入抽成比例"
          />
          <span>%</span>
        </a-form-model-item>
        <a-form-model-item label="供货商类型" prop="type">
          <a-select v-model="businessForm.type" placeholder="请选择供货商类型" :disabled='disabled_edit'>
            <a-select-option value="0"> 个人 </a-select-option>
            <a-select-option value="1"> 企业 </a-select-option>
            <a-select-option value="2"> 个体工商户 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="资料证书" prop="certificate">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                if (disabled_edit) {
                  return
                }
                businessForm.certificate = e.data
              }
            "
            @deleteImg="() => {
              if (disabled_edit) {
                return
              }
              businessForm.certificate = ''
            }"
            :imgSrc="businessForm.certificate"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="身份证正面" prop="id_card_front">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                if (disabled_edit) {
                  return
                }
                businessForm.id_card_front = e.data
              }
            "
            @deleteImg="(e) => {
              if (disabled_edit) {
                return
              }
              businessForm.id_card_front = ''
            }"
            :imgSrc="businessForm.id_card_front"
            imgSizeText="750*320"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="身份证反面" prop="id_card_reverse">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                if (disabled_edit) {
                  return
                }
                businessForm.id_card_reverse = e.data
              }
            "
            @deleteImg="(e) => {
              if (disabled_edit) {
                return
              }
              businessForm.id_card_reverse = ''
            }"
            :imgSrc="businessForm.id_card_reverse"
            imgSizeText="750*320"
          >
          </cyyUploadImg>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { creatSupplier, editSupplier, supplierList, supplierDel, setSupplierStatus } from '@/api/purchase/purchase'
import tabList from '@/views/saas/components/tabList.vue'
import { cyyUploadImg } from '@/components/CyyUi'
import { generateTokenBySupplier } from '@/api/auth'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Address } from '@/components'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '供货商信息',
    scopedSlots: {
      customRender: 'user',
    },
    width: 280,
  },
  // {
  //   title: '用户',
  //   dataIndex: 'supplier_name'
  // },
  {
    title: '手机号',
    dataIndex: 'tel',
  },
  {
    title: '商品数量',
    dataIndex: 'goods_num',
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '入驻/申请时间',
    dataIndex: 'addtime',
    scopedSlots: {
      customRender: 'addtime',
    },
    sorter: (a, b) => a.addtime - b.addtime,
  },
  {
    title: '操作',
    width: 180,
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  components: {
    tabList,
    cyyUploadImg,
    Address,
  },
  data() {
    let checkPic = (rule, value, callback) => {
      if (!value) {
        if (rule.field == 'logo') {
          callback(new Error('请上传供货商logo'))
        }
        if (rule.field == 'certificate') {
          callback(new Error('请上传资料证书'))
        }
        if (rule.field == 'id_card_front') {
          callback(new Error('请上传身份证正面'))
        }
        if (rule.field == 'id_card_reverse') {
          callback(new Error('请上传身份证反面'))
        }
      } else {
        callback()
      }
    }
    return {
      tabList: [
        {
          key: 'saasSupplierList',
          name: '供货商列表',
        },
        // {
        //   key: 'saasSupplierTrans',
        //   name: '转单记录',
        // },
        // {
        //   key: 'saasSupplierPurchase',
        //   name: '采购记录',
        // },
        {
          key: 'saasSupplierBalance',
          name: '余额记录',
        },
      ],
      // 搜索参数
      queryParam: {
        page: 1,
        limit: 10,
        tel: '',
        name: '',
        status: '-1',
      },
      // 数据总数
      totalCount: 0,
      columns,
      list: [],
      // 是否显示创建供货商弹窗
      showCreated: false,
      // 新增 编辑供货商的表单
      businessForm: {
        supplier_name: '',
        rate: 0,
        id: '',
        logo: '',
        name: '',
        tel: '',
        password: '',
        email: '',
        type: '',
        certificate: '',
        id_card_front: '',
        id_card_reverse: '',
        sale_day: '',
      },
      businessRules: {
        supplier_name: [{ required: true, message: '请输入供货商名称', trigger: 'blur' }],
        logo: [{ required: true, validator: checkPic, trigger: 'change' }],
        name: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入供货商电话号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入供货商密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入供货商邮箱', trigger: 'blur' }],
        sale_day: [{ required: true, message: '请输入售后时间', trigger: 'blur' }],
        rate: [{ required: true, message: '请输入抽成比例', trigger: 'blur' }],
        type: [{ required: true, message: '请选择供货商类型', trigger: 'blur' }],
        certificate: [{ required: true, validator: checkPic, trigger: 'change' }],
        id_card_front: [{ required: true, validator: checkPic, trigger: 'change' }],
        id_card_reverse: [{ required: true, validator: checkPic, trigger: 'change' }],
      },
      // 按钮是否在加载中
      btnLoading: false,
      address_info: {
        province_id: '',
        district_id: '',
        city_id: '',
      },
      disabled: false,
      disabled_edit: false
    }
  },
  created() {
    this.getList()

    let goodsAgent = storage.get('goodsAgent')
    if (goodsAgent) {
      this.disabled = true
    }
  },
  computed: {
    getStatus() {
      return (status) => {
        let str

        switch (parseInt(status)) {
          case 0:
            str = '未审核'
            break

          case 1:
            str = '已通过'
            break

          case 2:
            str = '已拒绝'
            break
        }
        return str
      }
    },
  },
  filters: {
    orderStatus(val) {
      if (val == 0) {
        return 'background-color:#faad14;'
      }

      if (val == 1) {
        return 'background-color:#65c817;'
      }

      if (val == 2) {
        return 'background-color:#ff0000;'
      }
    },
  },
  methods: {
    setSupplierStatus(status) {},
    onInSupplier(item) {
      console.log(item.id, item.name)
      storage.set('currentStoreUsername', this.$store.state.user.info.username)
      generateTokenBySupplier({ supplier_id: item.id, username: item.name })
        .then((res) => {
          console.log(res)
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSupplier', true)
            storage.set('storeId', item.id)
            storage.set('isSaasSupplier', true)
            storage.remove('isSaasStore')
            storage.remove('isPlatform')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },
    // 重置搜索参数
    resetQueryParams() {
      this.queryParam.page = 1
      this.queryParam.tel = ''
      this.queryParam.name = ''
      this.queryParam.status = -1
      this.getList()
    },
    // 关闭弹窗的回调
    closeModal() {
      this.$refs['ruleForm'].resetFields()
      this.businessForm.supplier_name = ''
      this.businessForm.id = ''
      this.businessForm.logo = ''
      this.businessForm.name = ''
      this.businessForm.tel = ''
      this.businessForm.password = ''
      this.businessForm.email = ''
      this.businessForm.type = ''
      this.businessForm.certificate = ''
      this.businessForm.id_card_front = ''
      this.businessForm.id_card_reverse = ''
      this.businessForm.sale_day = ''
      this.businessForm.rate = 0
      this.address_info = {
        province_id: '',
        district_id: '',
        city_id: '',
      }
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.page = e
      this.getList()
    },
    // 获取数据
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      const res = await supplierList(this.queryParam)
      if (res.code == 0) {
        this.list = res.data.list
        this.totalCount = res.data.count
      }
      hide()
    },
    // 点击新增供货商
    editSupplier() {
      if (this.disabled_edit) {
        this.showCreated = false
        return
      }
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let { address_info } = this,
            businessForm = JSON.parse(JSON.stringify(this.businessForm))
          businessForm.rate = parseFloat(businessForm.rate).toFixed(2)

          if (!address_info) {
            this.$message.error('请选择省市区~')
            return
          }
          this.btnLoading = true
          let res

          if (!businessForm.id) {
            res = await creatSupplier({ ...businessForm, ...address_info })
          } else {
            res = await editSupplier({ ...businessForm, ...address_info })
          }

          if (res.code == 0) {
            this.showCreated = false
            this.getList()
            this.address_info = {
              province_id: '',
              district_id: '',
              city_id: '',
            }
            this.$message.success('操作成功')
          } else {
            this.$message.error(res.msg)
          }
          this.btnLoading = false
        } else {
          return false
        }
      })
    },

    // 点击编辑供货商
    toEdit(scope, disabled_edit = 0) {
      this.businessForm.supplier_name = scope.supplier_name
      this.businessForm.email = scope.email
      this.businessForm.sale_day = scope.sale_day
      this.businessForm.id = scope.id
      this.businessForm.logo = scope.logo
      this.businessForm.name = scope.name
      this.businessForm.tel = scope.tel
      this.businessForm.password = scope.password
      this.businessForm.email = scope.email
      this.businessForm.type = scope.type
      this.businessForm.certificate = scope.certificate
      this.businessForm.id_card_front = scope.id_card_front
      this.businessForm.id_card_reverse = scope.id_card_reverse
      this.businessForm.rate = scope.rate
      this.showCreated = true

      this.address_info = {
        province_id: scope.province_id,
        district_id: scope.district_id,
        city_id: scope.city_id,
      }
      this.disabled_edit = !!disabled_edit
    },
    // 点击修改供货商状态
    delSupplier(scope, status) {
      const that = this
      let arr = [1, 2]
      if (arr.indexOf(status) !== -1) {
        this.$confirm({
          title: '是否确认当前操作？',
          async onOk() {
            const res = await setSupplierStatus({ supplier_id: scope.id, status: status })
            if (parseInt(res.code) === 0) {
              that.getList()
            }
          },
          onCancel() {},
        })
      } else {
        this.$confirm({
          title: '是否删除供货商？',
          async onOk() {
            const res = await supplierDel({ supplier_id: scope.id })
            if (res.code == 0) {
              that.getList()
            }
          },
          onCancel() {},
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    margin-top: 11px;
    display: flex;
    align-items: center;
    margin-right: 15px;
  }
  .ant-btn {
    margin-top: 11px;
  }
}
.tip {
  line-height: normal;
  margin-bottom: 0;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.tagBox {
  display: flex;
  align-items: center;
}

.tag {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
}
</style>
